<template>
  <el-page-header @back="router.go(-1)" title="返回">
    <template #content>
      <span>{{foodForm.id ? '编辑':'添加'}}菜品</span>
    </template>
  </el-page-header>

  <div class="content">
    <el-form ref="foodFormRef" :model="foodForm" :rules="foodFormRule" :inline="false" label-width="160px">

      <el-form-item label="名称" prop="name">
        <el-input v-model="foodForm.name" placeholder="请输入名称" maxlength="20"/>
      </el-form-item>

      <el-form-item label="分类" prop="categoryId">
        <el-select style="width:200px" v-model="foodForm.categoryId" placeholder="请选择分类">
          <el-option v-for="(item, index) in categoryList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input v-model="foodForm.price" placeholder="请输入价格" maxlength="12"/>
      </el-form-item>

      <el-form-item label="口味">
        <div>
          <div v-for="selectedFlavor in selectedFlavorList" style="margin-bottom: 10px;">
            <el-select v-model="selectedFlavor.name" @change="handleChangeFlavor" style="width: 120px;margin-right: 20px;">
              <el-option v-for="item in flavorList" :key="item.name" :label="item.name" :value="item.name" />
            </el-select>

            <el-select
                v-model="selectedFlavor.item" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" style="width: 280px">
              <el-option v-for="item in flavorItemList" :key="item" :label="item" :value="item" />
            </el-select>
          </div>
          <el-button type="success" @click="handleAddFlavorItem">添加口味</el-button>
        </div>
      </el-form-item>

      <el-form-item label="菜品图片:" prop="image">

        <el-upload
            class="avatar-uploader"
            action="http://localhost/file/upload"
            :headers="{token:token}"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="foodForm.photo" :src="foodForm.photo" style="width:178px;height:178px;" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="描述">
        <el-input v-model="foodForm.description" type="textarea" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handleCancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";

import {saveFood,findById} from "@/api/food"
import {getCategoryList} from "@/api/category"
import {getFlavorList} from "@/api/flavor"

import { ElMessage } from 'element-plus'

const router = useRouter();
const route = useRoute();

let categoryList = reactive([]);

let foodFormRef = reactive(null);
let foodForm = reactive({
  id:null,
  name: null,
  categoryId:null,
  price:null,
  flavor:null,
  photo:null,
  description:null,
});
let foodFormRule = reactive({
  name: [
    {
      required: true,
      trigger: 'blur'
    }
  ],
  price: [
    {
      required: true,
      trigger: 'blur'
    }
  ],
  categoryId: [
    {
      required: true,
      trigger: 'blur'
    }
  ]
})

const token = sessionStorage.getItem("token");

const flavorList = []
let flavorItemList = reactive([]);

let selectedFlavorList= reactive([ { "name": null, "item": [] } ]);

//加载菜品分类信息
getCategoryList().then(resp=>{
  categoryList.push(... resp.data);
})

//加载口味数据字典
getFlavorList({}).then((resp)=>{
  if(resp.data){
    resp.data.forEach((item)=>{
      item.value = JSON.parse(item.value);
      flavorList.push(item);
    })
  }
})


if(route.query.foodId){
  //根据id查找
  findById(route.query.foodId).then((resp)=>{
    let food = resp.data;
    foodForm.id = food.id;
    foodForm.name = food.name;
    foodForm.categoryId = food.categoryId;
    foodForm.price = food.price;
    foodForm.flavor = food.flavor;
    foodForm.photo = food.photo;
    foodForm.description = food.description;

    if(food.flavor){
      selectedFlavorList.length = 0;
      selectedFlavorList.push(... JSON.parse(food.flavor));
    }
  }).catch((error)=>{

  })
}


const handleAddFlavorItem=()=>{
  selectedFlavorList.push({"name":null,"item":[]});
}

const handleChangeFlavor=(value)=>{
  for(let item of flavorList){
    if(item.name == value){
      flavorItemList.length = 0;
      flavorItemList.push(... item.value);
    }
  }
}


//图片上传相关方法
const handleAvatarSuccess=(resp, file)=>{
  foodForm.photo = resp.data;
}

const beforeAvatarUpload=(file)=>{
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
}


let handleSave = () => {
  //判断是否校验通过
  foodFormRef.validate((valid) => {
    if (valid) {
      let flavorList = [];
      for(let item of selectedFlavorList){
        if(item.name){
          flavorList.push(item);
        }
      }
      foodForm.flavor = JSON.stringify(flavorList);
      saveFood(foodForm.id,foodForm).then((resp) => {
        //提示并且返回列表
        router.push({path: '/food/list'});
      });
    }
  });
}
</script>

<style scoped>
.content {
  margin-top: 40px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
